package com.myphoto.base.config.interceptor;

import com.myphoto.base.config.properties.IConfig;
import com.myphoto.base.log.service.LogService;
import com.myphoto.base.mybatis.log.entity.TbLogUrlEntity;
import com.myphoto.base.util.UserFun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/** 登录拦截器 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private LogService logService;
    @Autowired
    IConfig config;
    @Value(value = "${spring.application.name}")
    private String xmmc;

    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("WatchExecuteTime");

    /**
     * 在业务处理器处理请求之前被调用
     * 如果返回false
     * 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
     * <p>
     * 如果返回true
     * 执行下一个拦截器,直到所有的拦截器都执行完毕
     * 再执行被拦截的Controller
     * 然后进入拦截器链,
     * 从最后一个拦截器往回执行所有的postHandle()
     * 接着再从最后一个拦截器往回执行所有的afterCompletion()
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("==============执行顺序: 1、preHandle================");
        long beginTime = System.currentTimeMillis(); //开始时间
        startTimeThreadLocal.set(beginTime);
        //如果不是映射到方法直接通过
        boolean isHandlerMethod = handler instanceof HandlerMethod;
        if (!isHandlerMethod) {
            return true;
        }
        return true;
    }

    /**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        //System.out.println("==============执行顺序: 2、postHandle================");
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        //System.out.println("==============执行顺序: 3、afterCompletion================");
        boolean url_record_enable = Boolean.parseBoolean(config.getConfig().getUrl_record_enable());
        int url_record_threshold = Integer.parseInt(config.getConfig().getUrl_record_threshold());
        if(!url_record_enable){
            return;
        }
        //URL请求时间记录
        long endTime = System.currentTimeMillis();
        Long executeTime = endTime - startTimeThreadLocal.get();
        try{
            String url = request.getRequestURI();
            //URL请求耗时大于2秒才记录
            if(executeTime>=url_record_threshold){
                TbLogUrlEntity logUrlEntity = new TbLogUrlEntity();
                logUrlEntity.setId(UserFun.getUUID32());
                logUrlEntity.setRecordTime(new Date());
                logUrlEntity.setUrlInfo(url);
                logUrlEntity.setXhsj(executeTime.intValue());
                logUrlEntity.setXmmc(xmmc);
                logUrlEntity.setUsername("");
                logService.saveUrlMonitor(logUrlEntity);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
